from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
import sqlite3
from typing import List

app = FastAPI()

# windows
db_path = "E:\develop\sqlite/db.sqlite"

# ubuntu下直接访问
# db_path = "/home/boole/tools/sqlite/db.sqlite"

@app.get("/query/")
async def query_data(sql: str):
    try:
        print("请求参数：",sql)
        sql = sql.replace("```sql","").replace("```","")
        print("请求参数处理后：",sql)
        # Parse the SQL request from the query string
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        cursor.execute(sql)
        rows = cursor.fetchall()
        result = [str(row) for row in rows]

        conn.close()
        return result
    except Exception as e:
        # raise HTTPException(status_code=500, detail=str(e))
        print(str(e))
        return []


@app.post("/execute/")
async def execute_data(sql: str):
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        cursor.execute(sql)
        rows = cursor.fetchall()
        result = [str(row) for row in rows]

        conn.close()
        return {"result": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8002)